
package com.zhu.salesmanagement.utils;

import java.text.SimpleDateFormat;

import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.net.Uri;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;

import com.zhu.salesmanagement.VisitTaskListActivity;
import com.zhu.salesmanagement.common.Actions;
import com.zhu.salesmanagement.common.GetGpsLocation;
import com.zhu.salesmanagement.models.VerifyUserResult;
import com.zhu.salesmanagement.models.VisitTaskInfo;
import com.zhu.salesmanagement.provider.SalesSettings;

/**
 * 全局引用
 * 
 */

public class Util {
    static double DEF_PI = 3.14159265359; // PI
    static double DEF_2PI = 6.28318530712; // 2*PI
    static double DEF_PI180 = 0.01745329252; // PI/180.0
    static double DEF_R = 6370693.5; // radius of earth

    public static VerifyUserResult mVerifyUserResult = null; //登录结果
    public static GetGpsLocation mGetGpsLocation = null;
    public static boolean isFirst = false;

    /**
     * 保存门店签入信息
     * @param context 上下问
     * @param visitTaskInfo 拜访门店信息
     * @param lat 经纬度
     * @param lng 经纬度
     * @param isSaveType 是否保存iVisitCategory 此参数从附近门店或者地图拜访需要保存方便同步上传
     */
    public static boolean saveStoresCheckinInfo(Context context, VisitTaskInfo visitTaskInfo,
            double lat, double lng, boolean isSaveType) {
        try {
            ContentValues values = new ContentValues();
            values.put(SalesSettings.VisitedStoresColumns.STOREID, visitTaskInfo.id);
            values.put(SalesSettings.VisitedStoresColumns.CHECKIN_LAT, lat);
            values.put(SalesSettings.VisitedStoresColumns.CHECKIN_LNG, lng);
            values.put(SalesSettings.VisitedStoresColumns.CHECKIN_TIME, visitTaskInfo.mCheckinTime);

            if (Actions.DEBUG) {
                Log.e("zhu", "checkin id=" + visitTaskInfo.mDbId);
            }
            if (visitTaskInfo.mDbId == -1) {
                if (isSaveType) {
                    values.put(SalesSettings.VisitedStoresColumns.VISITCATEGOR, visitTaskInfo.type);
                }
//                values.put(SalesSettings.VisitedStoresColumns.DTASKACTUALID,
//                        Util.getDatingTaskActualID(Util.mVerifyUserResult.id, visitTaskInfo.id));
                Uri uri = context.getContentResolver().insert(
                        SalesSettings.VisitedStoresColumns.CONTENT_URI, values);
                visitTaskInfo.mDbId = Long.parseLong(uri.getPathSegments().get(1));
            } else {
//                values.put(SalesSettings.VisitedStoresColumns.DTASKACTUALID,
//                        Util.getDatingTaskActualID(Util.mVerifyUserResult.id, visitTaskInfo.id));
                context.getContentResolver()
                        .update(SalesSettings.VisitedStoresColumns.getContentUri(
                                visitTaskInfo.mDbId, false), values, null, null);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 保存门店签出信息
     * @param context 上下问
     * @param visitTaskInfo 拜访门店信息
     * @param lat 经纬度
     * @param lng 经纬度
     */
    public static boolean saveStoresCheckoutInfo(Context context, VisitTaskInfo visitTaskInfo,
            double lat, double lng) {
        try {
            ContentValues values = new ContentValues();
            values.put(SalesSettings.VisitedStoresColumns.STOREID, visitTaskInfo.id);
            values.put(SalesSettings.VisitedStoresColumns.CHECKOUT_LAT, lat);
            values.put(SalesSettings.VisitedStoresColumns.CHECKOUT_LNG, lng);
            values.put(SalesSettings.VisitedStoresColumns.CHECKOUT_TIME,
                    visitTaskInfo.mCheckoutTime);
            if (Actions.DEBUG) {
                Log.e("zhu", "checkout id=" + visitTaskInfo.mDbId);
            }
            if (visitTaskInfo.mDbId == -1) {
                Uri uri = context.getContentResolver().insert(
                        SalesSettings.VisitedStoresColumns.CONTENT_URI, values);
                visitTaskInfo.mDbId = Long.parseLong(uri.getPathSegments().get(1));
            } else {
                context.getContentResolver()
                        .update(SalesSettings.VisitedStoresColumns.getContentUri(
                                visitTaskInfo.mDbId, false), values, null, null);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 保存歇业门店
     * @param context 上下问
     * @param dbid 数据库记录ID
     */
    public static boolean saveStoresClose(Context context, long dbid) {
        try {
            ContentValues values = new ContentValues();
            context.getContentResolver().update(
                    SalesSettings.VisitedStoresColumns.getContentUri(dbid, false), values, null,
                    null);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取DatingTaskActualID
     * @param eid 业务员ID
     * @param cid 客户ID
     */
    public static String getDatingTaskActualID(String eid, String cid) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        Date curDate = new Date(System.currentTimeMillis());
        String str = formatter.format(curDate);
        return str + eid + cid;
    }

    /**
     * 获取DatingTaskActualID
     * @param eid 业务员ID
     * @param cid 客户ID
     */
    public static String getDatingTaskActualID(String eid, String cid, long time) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        long tmpTime = time == 0 ? System.currentTimeMillis() : time;
        Date curDate = new Date(tmpTime);
        String str = formatter.format(curDate);
        return str + eid + cid;
    }

    /**
     * 格式化时间
     * @param time 时间
     */
    public static String getFormatTime(long time) {
    	String str = "";
    	if(time > 0){
    		 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    	        Date curDate = new Date(time);
    	        str = formatter.format(curDate);
    	}
        return str;
    }

    public static double GetShortDistance(double lon1, double lat1, double lon2,
            double lat2) {
        double ew1, ns1, ew2, ns2;
        double dx, dy, dew;
        double distance;
        // 角度转换为弧度
        ew1 = lon1 * DEF_PI180;
        ns1 = lat1 * DEF_PI180;
        ew2 = lon2 * DEF_PI180;
        ns2 = lat2 * DEF_PI180;
        // 经度差
        dew = ew1 - ew2;
        // 若跨东经和西经180 度，进行调整
        if (dew > DEF_PI)
            dew = DEF_2PI - dew;
        else if (dew < -DEF_PI)
            dew = DEF_2PI + dew;
        dx = DEF_R * Math.cos(ns1) * dew; // 东西方向长度(在纬度圈上的投影长度)
        dy = DEF_R * (ns1 - ns2); // 南北方向长度(在经度圈上的投影长度)
        // 勾股定理求斜边长
        distance = Math.sqrt(dx * dx + dy * dy);
        return distance;
    }

    public static double GetLongDistance(double lon1, double lat1, double lon2,
            double lat2) {
        double ew1, ns1, ew2, ns2;
        double distance;
        // 角度转换为弧度
        ew1 = lon1 * DEF_PI180;
        ns1 = lat1 * DEF_PI180;
        ew2 = lon2 * DEF_PI180;
        ns2 = lat2 * DEF_PI180;
        // 求大圆劣弧与球心所夹的角(弧度)
        distance = Math.sin(ns1) * Math.sin(ns2) + Math.cos(ns1)
                * Math.cos(ns2) * Math.cos(ew1 - ew2);
        // 调整到[-1..1]范围内，避免溢出
        if (distance > 1.0)
            distance = 1.0;
        else if (distance < -1.0)
            distance = -1.0;
        // 求大圆劣弧长度
        distance = DEF_R * Math.acos(distance);
        return distance;
    }

    public static int getVerCode(Context context) {
        int verCode = 0;
        try {
            verCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            if (Actions.DEBUG) {
                e.printStackTrace();
            }
        }
        return verCode;
    }

    /**
     * 获取版本号
     * @param context
     */
    public static String getVerName(Context context) {
        String verName = null;
        try {
            verName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            if (Actions.DEBUG) {
                e.printStackTrace();
            }
        }
        return verName;
    }

    /**
     * 检测是否能离线登录
     * @param context
     */
    public static boolean canOfflineLogin(Context context) {
        Cursor cursor = null;
        boolean isCheckin = false;
        boolean isCheckout = false;
        try {
            String where = SalesSettings.VisitedStoresColumns.STOREID + " = \'" + VisitTaskListActivity.STARTCHECKID
                    + "\' OR " + SalesSettings.VisitedStoresColumns.STOREID +" = \'" + VisitTaskListActivity.STOPCHECKID + "\'";
            cursor = context.getContentResolver().query(
                    SalesSettings.VisitedStoresColumns.CONTENT_URI, null, where, null, null);
            int cidindex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.STOREID);
            int checkindex = cursor
                    .getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKIN_TIME);
            while (cursor.moveToNext()) {
                String tid = cursor.getString(cidindex);
                String checkintime = cursor.getString(checkindex);
                if (tid.equals(VisitTaskListActivity.STARTCHECKID) && checkintime != null
                        && checkintime.length() > 1) {
                    isCheckin = true;
                } else if (tid.equals(VisitTaskListActivity.STOPCHECKID) && checkintime != null
                        && checkintime.length() > 1) {
                    isCheckout = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
                cursor = null;
            }
            if (isCheckin && !isCheckout) {
                return true;
            }
            return false;
        }
    }

    public static boolean isEndVisit(Context context) {
        return true;
//        Cursor cursor = null;
//        boolean isCheckin = false;
//        boolean isCheckout = false;
//        try {
//            String where = SalesSettings.VisitedStoresColumns.STOREID + " = \'" + VisitTaskListActivity.STARTCHECKID
//                    + "\' OR " + SalesSettings.VisitedStoresColumns.STOREID + " = \'" + VisitTaskListActivity.STOPCHECKID + "\'";
//            cursor = context.getContentResolver().query(
//                    SalesSettings.VisitedStoresColumns.CONTENT_URI, null, where, null, null);
//            int cidindex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.STOREID);
//            int checkindex = cursor
//                    .getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKIN_TIME);
//            while (cursor.moveToNext()) {
//                String tid = cursor.getString(cidindex);
//                String checkintime = cursor.getString(checkindex);
//                if (tid.equals(VisitTaskListActivity.STARTCHECKID) && checkintime != null
//                        && checkintime.length() > 1) {
//                    isCheckin = true;
//                } else if (tid.equals(VisitTaskListActivity.STOPCHECKID) && checkintime != null
//                        && checkintime.length() > 1) {
//                    isCheckout = true;
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            if (cursor != null) {
//                cursor.close();
//                cursor = null;
//            }
//            if (!isCheckin || (isCheckin && isCheckout)) {
//                return true;
//            }
//            return false;
//        }
    }

    static public float getScreenDensity(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()
                .getMetrics(dm);
        return dm.density;
    }

    static public int dipToPx(Context context, int dip) {
        return (int) (dip * getScreenDensity(context) + 0.5f);
    }

    static public int spToPx(Context context, float sp){
        return (int) (sp*getScreenScaledDensity(context) + 0.5f );
    }

    static public float getScreenScaledDensity(Context context){
        DisplayMetrics dm = new DisplayMetrics();
        ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(dm);
        return dm.scaledDensity;
    }

    /**
     * 获取门店数据库主键ID
     * @param context
     * @param storeid 客户id
     */
    public static long getVisitedStoreDbID(Context context, String storeid) {
        long id = -1;
        Cursor cursor = null;
        try {
            String where = SalesSettings.VisitedStoresColumns.STOREID + " = \'" + storeid + "\'";
            cursor = context.getContentResolver().query(
                    SalesSettings.VisitedStoresColumns.CONTENT_URI, null, where, null, null);
            int index = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns._ID);
            while (cursor.moveToNext()) {
                id = cursor.getLong(index);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
                cursor = null;
            }
            return id;
        }
    }

    /**
     * 获取当前时间格式字符串
     */
    public static String getFormatTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());
        String str = formatter.format(curDate);
        return str;
    }
}
